package com.rxst.msg.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.rxst.msg.base.ResponseVo;
import com.rxst.msg.dto.excel.MsgxUserExcelDto;
import com.rxst.msg.dto.excel.MsgxUserExcelErrorDto;
import com.rxst.msg.dto.save.MsgxUserSaveDto;
import com.rxst.msg.dto.save.user.LoginUserDto;
import com.rxst.msg.dto.save.user.UpdateCommenUserDto;
import com.rxst.msg.dto.save.user.UpdatePasswordDto;
import com.rxst.msg.dto.search.MsgxUserSearchDto;
import com.rxst.msg.dto.update.MsgxUserUpdateDto;
import com.rxst.msg.entity.MsgxUserEntity;
import com.rxst.msg.enums.constant.UploadConstant;
import com.rxst.msg.server.MsgxUserService;
import com.rxst.msg.sso.entity.UserContext;
import com.rxst.msg.utils.ExcelUtils;
import com.rxst.msg.utils.JwtUtils;
import com.rxst.msg.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 用户表
 *
 * @author rxst
 * @email rxst@gmail.com
 * @date 2021-08-19 11:47:01
 */
@RestController
@RequestMapping("user")
@Api(value = "用户表", tags = "用户表")
@Slf4j
public class MsgxUserController {

    @Autowired
    private MsgxUserService service;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 列表
     */
    @PostMapping("/list")
    @ApiOperation("列表")
    public ResponseVo List(@RequestBody MsgxUserSearchDto dto) {
        return ResponseVo.ok(service.list(dto));
    }

    /**
     * 分页Function
     */
    @PostMapping("/page")
    @ApiOperation("分页")
    public ResponseVo page(@RequestBody MsgxUserSearchDto dto) {
        return ResponseVo.ok(service.page(dto));
    }

    /**
     * 详情
     */
    @GetMapping("/info")
    @ApiOperation("详情")
    public ResponseVo info(String id) {
        return ResponseVo.ok(service.getById(id));
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation("保存")
    public ResponseVo save(@RequestBody MsgxUserSaveDto dto) {
        //校验类型
        Boolean flag = service.saveEntity(dto);
        if (!flag) {
            return ResponseVo.error("账号已存在");
        }
        return ResponseVo.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @ApiOperation("修改")
    public ResponseVo update(@RequestBody MsgxUserUpdateDto dto) {
        MsgxUserEntity entity = BeanUtil.toBean(dto, MsgxUserEntity.class);
        return ResponseVo.ok(service.updateEntity(entity));
    }

    /**
     * 批量删除
     */
    @DeleteMapping("/delete")
    @ApiOperation("批量删除")
    public ResponseVo delete(@RequestParam(value = "ids") List<Long> ids) {
        if (CollUtil.isNotEmpty(ids)) {
            service.removeByIds(ids);
        } else {
            return ResponseVo.error("参数不能为空");
        }
        return ResponseVo.ok();
    }

    /**
     * 批量逻辑删除
     */
    @DeleteMapping("/delete/logic")
    @ApiOperation("批量逻辑删除")
    public ResponseVo deleteLogic(@RequestParam(value = "ids") List<Long> ids) {
        if (CollUtil.isNotEmpty(ids)) {
            service.deleteLogicByIds(ids);
        } else {
            return ResponseVo.error("参数不能为空");
        }
        return ResponseVo.ok();
    }

    @ApiOperation("管理员用户登录")
    @PostMapping("/login")
    public ResponseVo login(@RequestBody LoginUserDto user) {
        log.info("获取到的参数是：" + user);
        UserContext userContext = service.login(user);
        if (userContext == null) {
            return ResponseVo.error("账号或者密码错误，请重新输入");
        }
        return ResponseVo.ok(userContext);
    }

    @ApiOperation("用户退出登录")
    @GetMapping("/logOut")
    public ResponseVo logOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
            TokenUtils.removeToken(token);
        }
        return ResponseVo.ok();
    }

    @ApiOperation("修改密码")
    @PostMapping("/update/password")
    public ResponseVo updatePassword(@RequestBody UpdatePasswordDto dto) {
        log.info("获取到的参数是：" + dto);
        if (dto.getId() == null) {
            return ResponseVo.error("参数不能为空");
        }
        MsgxUserEntity userEntity = service.getById(dto.getId());
        if (userEntity == null) {
            return ResponseVo.error("未找到数据");
        }
        service.updatePassword(dto, userEntity);
        return ResponseVo.ok();
    }

    @PostMapping("/update/common")
    @ApiOperation("编辑普通用户信息")
    public ResponseVo updateCommonUser(@RequestBody UpdateCommenUserDto dto) {
        log.info("获取到的参数是：" + dto);
        service.updateCommonUser(dto);
        return ResponseVo.ok();
    }

    /**
     * 用户导入
     */
    @ApiOperation("用户导入")
    @PostMapping("import")
    public ResponseVo importData(@RequestParam("file") MultipartFile multipartFile) {
        return service.importData(multipartFile);
    }

    /**
     * 用户导出
     */
    @GetMapping("export")
    @ApiOperation("用户导出")
    public void export(HttpServletResponse response) {
        List<MsgxUserEntity> list = service.list();
        Map<Integer, List> map = new HashMap<>();
        map.put(0, list);
        ExcelUtils.write(response, "用户导出", "用户导出.xlsx", map);
    }

    /**
     * 用户错误数据导出
     */
    @GetMapping("error/export")
    @ApiOperation("用户错误数据导出")
    public void export(String key, HttpServletResponse response) {

        if (UploadConstant.ERROR_UPLOAD.containsKey(key)) {
            MsgxUserExcelErrorDto errorDto = UploadConstant.ERROR_UPLOAD.get(key);
            List<MsgxUserExcelDto> excelDto = errorDto.getExcelDto();
            Map<Integer, List> map = new HashMap<>();
            map.put(0, excelDto);
            UploadConstant.ERROR_UPLOAD.remove(key);
            if (CollUtil.isNotEmpty(UploadConstant.ERROR_UPLOAD)) {
                Iterator<Map.Entry<String, MsgxUserExcelErrorDto>> iterator = UploadConstant.ERROR_UPLOAD.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, MsgxUserExcelErrorDto> entry = iterator.next();
                    MsgxUserExcelErrorDto dto = entry.getValue();
                    if (dto != null && DateUtil.betweenDay(DateUtil.date(), dto.getDate(), false) >= 1) {
                        iterator.remove();
                    }
                }
            }
            ExcelUtils.write(response, "用户导入错误数据", "用户导入错误数据.xlsx", map);
        }

    }

    /**
     * 用户导入模板
     */
    @GetMapping("template/export")
    @ApiOperation("用户导入模板")
    public void downloadExcel(HttpServletResponse response) {
        ExcelUtils.downloadExcel(response, "templates/用户导入.xlsx");
    }
}
